package com.liang.controller;

import com.liang.pojo.Book;
import com.liang.service.BookService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller

public class BookController {

    @Autowired
    public BookService bookService;

    //   登录
    @PostMapping("/login")
    public String loginIn(@RequestParam("name") String name, @RequestParam("password")String password, HttpSession session) {
        if(name!=null&&password!=null){
            session.setAttribute("name",name);

        }
        return "redirect:/book/allBook";
    }

    //进入书籍首页
    @GetMapping("/book/allBook")
    public String goAllBookHome(Model model) {
        List<Book> allBookList = bookService.getAllBookList();
        model.addAttribute("list", allBookList);
        return "allBook";
    }

    @GetMapping("/book/bookFrom")
    public String goBookFrom(@Nullable @RequestParam("id") Integer id, Model model) {
        String title = "新增书籍";
        if (id != null) {
            Book book = bookService.getBookById(id);
            model.addAttribute("book", book);
            title = "编辑书籍";
        }
        model.addAttribute("title", title);
        return "bookFrom";
    }

    @PostMapping("/book/submit/form")
    public String submitForm(Book book, Model model) {
        System.out.println("book=>" + book.toString());
        if (book.getId() != null) {
            return updateBook(book);
        } else {
            return addBook(book);
        }
    }

    public String addBook(Book book) {
        int i = bookService.addBook(book);
        System.out.println("i=>" + i);
        return i > 0 ? "redirect:/book/allBook" : "redirect:/book/bookFrom";
    }

    public String updateBook(Book book) {
        int i = bookService.updateBook(book);
        return i > 0 ? "redirect:/book/allBook" : "redirect:/book/bookFrom";
    }

    //    删除数据
    @GetMapping("/book/delete")
    public String deleteBook(@RequestParam("id") Integer id) {
        bookService.deleteBook(id);
        return "redirect:/book/allBook";
    }

//    跳转文件上传页面
    @GetMapping("/file/uploadIndex")
    public String goUpload(HttpServletRequest rq,Model model){
        String realPath = rq.getServletContext().getRealPath("/upload");
        File fileArray = new File(realPath);
        System.out.println("fileArray----"+fileArray.listFiles());
        ArrayList<Object> lists = new ArrayList<>();
        if(fileArray.isDirectory()){
            File[] files = fileArray.listFiles();

            for (File file : files) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("url","/upload/"+file.getName());
                map.put("name",file.getName());
                System.out.println("url======"+"/upload/"+file.getName());
                System.out.println("name===="+file.getName());
                lists.add(map);
            }
        }
        model.addAttribute("fileList", lists);
        return "uploadIndex";
    }

    @PostMapping("/file/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest rq) throws IOException {
        System.out.println("file");
        System.out.println("file=>"+file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        if("".equals(originalFilename)){
            return "redirect:/index.jsp";
        }

        String path = rq.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
//        方式一：框架方法
        file.transferTo(new File(realPath+"/"+originalFilename));

//        方式二：原生io上传
//        InputStream is = file.getInputStream(); //文件输入流
//        OutputStream os = new FileOutputStream(new File(realPath,originalFilename)); //文件输出流
////读取写出
//        int len=0;
//        byte[] buffer = new byte[1024];
//        while ((len=is.read(buffer))!=-1){
//            os.write(buffer,0,len);
//            os.flush();
//        }
//        os.close();
//        is.close();
        return null;
    }

//    文件下载
    @GetMapping("/upload/{name}")
    public String download(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String  path = request.getServletContext().getRealPath("/upload");
        String  fileName = name;
        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
        File file = new File(path,fileName);
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();
        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();

        return null;
    }

}
